package com.example.yaja.yaja.upload;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by LCJ on 2017/4/25.
 */
public abstract class FileUploadUtil {
    /**
     * 单文件上传
     * @param multipartFile
     * @param httpServletRequest
     * @return
     * @throws IOException
     */

    public static String singleFileUpload(MultipartFile multipartFile, HttpServletRequest httpServletRequest) throws IOException {

        String realpath=httpServletRequest.getSession().getServletContext().getRealPath("/images");

        String fileTureName=fileType(multipartFile);

        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(realpath, fileTureName));
        return fileTureName;
    }

    /**
     * 多文件上传
     * @param multipartFile
     * @param httpServletRequest
     * @return
     * @throws IOException
     */
    public static String[] manyFileUpload(MultipartFile[] multipartFile, HttpServletRequest httpServletRequest) throws IOException {

        String [] imgPath=new String[3];

        int i=0;

        String realpath=httpServletRequest.getSession().getServletContext().getRealPath("/images");

        for(MultipartFile attach:multipartFile) {

            if(attach.isEmpty()) continue;

            String fileTureName= fileType(attach);

            imgPath[i]=fileTureName;

            FileUtils.copyInputStreamToFile(attach.getInputStream(), new File(realpath, fileTureName));

            i++;

        }
        return imgPath;
    }


    /**
     * 判断文件类型
     * @param multipartFile
     * @return
     */

    public static String fileType(MultipartFile multipartFile){

        String picTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        String picType = multipartFile.getContentType();

        String fileTureName = MD5Util.MD5(picTime);

        if (picType.equals("image/jpeg")) {

            fileTureName = fileTureName.concat(".jpg");


        } else if (picType.equals("image/png")) {

            fileTureName = fileTureName.concat(".png");

        } else if (picType.equals("image/bmp")) {

            fileTureName = fileTureName.concat(".bmp");

        } else if (picType.equals("image/gif")) {

            fileTureName = fileTureName.concat(".gif");

        } else if(picType.equals("image/jpg")) {

            fileTureName = fileTureName.concat(".jpg");

        }else {

            System.out.println("cuowu!");
        }

        return fileTureName;

    }
}
